<?php declare(strict_types=1);

namespace App\Services\Count;


use App\Models\Bi\BillLog;
use App\Models\Store;
use App\Models\StoreAllPayWayList;
use App\Models\User;
use App\Services\PrintSqlService;
use App\Util\TimeUtil;
use App\Util\WhereUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BillLogCountService
{
    protected function searchTime(array $where)
    {
        if (!empty($where["curHdIndex"])) {
            $curHdIndex = $where["curHdIndex"];
            $timeUtil = new TimeUtil();
            list($start, $end, $desc) = $timeUtil->get((int)$curHdIndex);
        } else {
            $start = $where["startDate"];
            $end = $where["endDate"];
        }
        if (empty($start) || empty($end)) {
            throw new \Exception("请开始时间和结束时间");
        }
        return [$start, $end];
    }

    public function setWhere($query, array $where)
    {
        $newWhere = WhereUtil::filterWhere($where);
        if (!empty($newWhere)) {
            $query->where($newWhere);
        }

        if (!empty($where["receive_model"])) {
            $query->where("receive_model", $where["receive_model"]);
        }

        if (!empty($where["agent_id"])) {
            //查询代理商
            if (is_array($where["agent_id"])) {
                $query->whereIn("agent_id", $where["agent_id"]);
            } else {
                $query->where("agent_id", $where["agent_id"]);
            }
        }

        if (!empty($where["store_id"])) {
            if (is_array($where["store_id"])) {
                $query->whereIn("store_id", $where["store_id"]);
            } else {
                $query->where("store_id", $where["store_id"]);
            }
        }

        if (!empty($where["pay_type"])) {
            $query->where("pay_type", $where["pay_type"]);
        }

        if (!empty($where["company"])) {
            $query->where("company", $where["company"]);
        }

        if (!empty($where["money"])) {
            $query->where("money", $where["money"]);
        }

        if (!empty($where["cashier_id"])) {
            $query->where("cashier_id", $where["cashier_id"]);
        }

        if (!empty($where["oem_id"])) {
            $query->where("oem_id", $where["oem_id"]);
        }

        if (!empty($where["agent1_id"])) {
            $query->where("agent1_id", $where["agent1_id"]);
        }

        if (!empty($where["agent2_id"])) {
            $query->where("agent2_id", $where["agent2_id"]);
        }

        if (!empty($where["agent3_id"])) {
            $query->where("agent3_id", $where["agent3_id"]);
        }

        if (!empty($where["agent4_id"])) {
            $query->where("agent4_id", $where["agent4_id"]);
        }
    }

    //分润明细查询
    public function commissionCountLog(array $where): array
    {
        $timeUtil = new TimeUtil();

        $query = BillLog::query()->from($timeUtil->getBillLogTableName($where["startDate"]));
        $this->setWhere($query, $where);
        $query->whereBetween("day", [$where["startDate"], $where["endDate"]]);
        $total = $query->count();

        $list = $query->select(["*"])->offset(($where["page"] - 1) * $where["pagesize"])->limit($where["pagesize"])->get()->toArray();

        //代理商  店铺信息
        $agentIds = array_column($list, "oem_id");
        $agentIds = array_merge($agentIds, array_column($list, "agent1_id"));
        $agentIds = array_merge($agentIds, array_column($list, "agent2_id"));
        $agentIds = array_merge($agentIds, array_column($list, "agent3_id"));
        $agentIds = array_merge($agentIds, array_column($list, "agent4_id"));

        $users = User::query()->whereIn("id", $agentIds)->get()->toArray();
        $users = array_combine(array_column($users, "id"), $users);
        $storeIds = array_column($list, "store_id");
        $storeIds = array_merge($storeIds, array_column($list, "store_pid"));
        $stores = Store::query()->whereIn("store_id", $storeIds)->get()->toArray();
        $stores = array_combine(array_column($stores, "store_id"), $stores);


        $companys = array_unique(array_column($list, "company"));
        $companys = StoreAllPayWayList::query()->whereIn("company", $companys)->get()->toArray();
        $companys = array_combine(array_column($companys, "company"), $companys);


        foreach ($list as $k => $v) {
            $v["oem_name"] = $v["agent1_name"] = $v["agent2_name"] = $v["agent3_name"] = $v["agent4_name"] = "";
            $v["store_name"] = $v["store_pname"] = "";

            if (isset($v["oem_id"])) {
                $v["oem_name"] = $users[$v["oem_id"]]["name"] ?? "";
            }
            if (isset($v["agent1_id"])) {
                $v["agent1_name"] = $users[$v["agent1_id"]]["name"] ?? "";
            }
            if (isset($v["agent2_id"])) {
                $v["agent2_name"] = $users[$v["agent2_id"]]["name"] ?? "";
            }
            if (isset($v["agent3_id"])) {
                $v["agent3_name"] = $users[$v["agent3_id"]]["name"] ?? "";
            }
            if (isset($v["agent4_id"])) {
                $v["agent4_name"] = $users[$v["agent4_id"]]["name"] ?? "";
            }

            if (isset($v["store_id"])) {
                $v["store_name"] = $stores[$v["store_id"]]["store_name"] ?? "";
            }
            if (isset($v["store_pid"])) {
                $v["store_pname"] = $stores[$v["store_pid"]]["store_name"] ?? "";
            }
            $v["company_name"] = "";
            if (isset($v["company"])) {
                $v["company_name"] = $companys[$v["company"] ?? ""]["company_desc"] ?? "";
            }
            $v["receipt_fee"] = bcsub((string)$v["total_fee"], (string)$v["refund_fee"], 2);
            $v["profit_column"] = $v[$where["profit_column"]];
            $v["fee_column"] = $v[$where["fee_column"]];
            $list[$k] = $v;
        }

        return [
            "total" => $total,
            "data" => $list
        ];
    }


    //商户交易统计

    /**
     * @param array $where curHdIndex   startDate  endDate  agentName StoreName payType company  money cashier
     * @return void
     * @throws \Exception
     */
    public function merchantGet(array $where): array
    {
        $util = new TimeUtil();
        list($start, $end) = $this->searchTime($where);
        // 商家实收 实际净额   交易金额/笔数   退款金额/笔数【隔日退+今日退】 手续费  会员支付金额  优惠金额/笔数
        //按照时间批量查询
        $timeBatch = $util->rangeTimeMonth($start, $end);
        //选择对应的表
        $timeMappTables = $util->getTable($timeBatch);
        //查询不能超过92天
        $count = [
            "total_fee" => 0,
            "refund_fee" => 0,
            "fee_amount" => 0,
            "pay_num" => 0,
            "refund_num" => 0,
            "next_refund_amount" => 0,
            "coupon_amount_yc" => 0,
            "coupon_num_yc" => 0,
            "coupon_amount_mc" => 0,
            "coupon_num_mc" => 0,
        ];
        foreach ($timeMappTables as $table => $time) {
            $days = [];
            foreach ($time as $v) {
                $days = array_merge($days, $util->getDayRange($v));
            }
            $query = BillLog::query()->from($table);
            $query->whereIn("day", $days);
            $result = $query->select([
                "day", "agent_id", "store_id", "receive_model", "ways_type", "pay_type",
//                商家实收 实际净额   交易金额/笔数   退款金额/笔数【隔日退+今日退】 手续费  会员支付金额  优惠金额/笔数
                DB::raw("sum(total_fee) as total_fee"),//交易金额
                DB::raw("sum(refund_fee) as refund_fee"),//退款金额
                DB::raw("sum(fee_amount) as fee_amount"),//手续费
                DB::raw("count(if(status=1,1,null)) as pay_num"), //交易笔数
                DB::raw("count(if(status=2,1,null)) as refund_num"),// 退款笔数
                DB::raw("sum(if(status=2 && refund_type=2,refund_fee,null)) as next_refund_amount"),//隔日退款
                DB::raw("count(if(status=2 && refund_type=2,1,null)) as next_refund_num"),//当日退笔数
                DB::raw("sum(if(coupon_type=1,coupon_amount,0)) as coupon_amount_yc"),//优惠金额- 优惠类型 预充值优惠券
                DB::raw("count(if(coupon_type=1,1,null)) as coupon_num_yc"),//优惠笔数- 预充值优惠券
                DB::raw("sum(if(coupon_type=2,coupon_amount,0)) as coupon_amount_mc"),//优惠金额- 优惠类型 免充值优惠券
                DB::raw("count(if(coupon_type=2,1,null)) as coupon_num_mc"),//优惠笔数- 免充值优惠券
            ])
                ->groupBy(["day", "agent_id", "store_id", "receive_model", "ways_type", "pay_type",])
                ->get()->toArray();
            foreach ($result as $v) {
                $count["total_fee"] = bcadd((string)$count["total_fee"], (string)$v["total_fee"], 2);
                $count["refund_fee"] = bcadd((string)$count["refund_fee"], (string)$v["refund_fee"], 2);
                $count["fee_amount"] += $v["fee_amount"];
                $count["pay_num"] += $v["pay_num"];
                $count["refund_num"] += $v["refund_num"];
                $count["next_refund_amount"] += $v["next_refund_amount"];
                $count["coupon_amount_yc"] += $v["coupon_amount_yc"];
                $count["coupon_num_yc"] += $v["coupon_num_yc"];
                $count["coupon_amount_mc"] += $v["coupon_amount_mc"];
                $count["coupon_num_mc"] += $v["coupon_num_mc"];
            }
        }
        return $count;
    }
    //门店交易统计

    /**
     * @param array $where curHdIndex  startDate   endDate
     * @return void
     */
    public function storeGet(array $where)
    {
        list($start, $end) = $this->searchTime($where);
        //门店  商户实际收款总额(元)  总交易笔数(笔)  微信总交易金额(元)  支付宝总交易金额(元)


    }

    /**
     * @param array $where
     * @return void
     */
    public function waysTypeGet(array $where)
    {
        list($start, $end) = $this->searchTime($where);
        // 门店id  商户名称  通道类型  交易总额

    }

    //4 本月数据  5 上月数据
    public function thisMonthGet(int $curHdIndex)
    {
        if (!in_array($curHdIndex, [4, 5])) {
            throw new \Exception("参数异常");
        }
    }

    //4 本月数据  5 上月数据
    public function lastMonthGet(int $curHdIndex)
    {
        if (!in_array($curHdIndex, [4, 5])) {
            throw new \Exception("参数异常");
        }
        //交易金额 交易笔数 退款金额  退款笔数 [隔日退]

    }


    /**
     * @param int $curHdIndex 1 今日数据   2 昨日数据 3 上周数据 4 本月数据  5 上月数据
     * @return void
     */
//    public function get(int $curHdIndex)
//    {
//        $where = [];
//        $timeUtil = new TimeUtil();
//        list($start, $end, $desc) = $timeUtil->get(2);
//        $query = BillLog::query()->from($timeUtil->getBillLogTableName($start));
//        //查询数据
////company	varchar	255	0	0	0	0	0				公司			utf8mb4	utf8mb4_general_ci	0	0	0	0	0	0	0
////coupon_type	tinyint	1	0	0	0	0	0			0	优惠类型 1-预充值优惠券  2-免充值优惠券					0	0	0	0	0	0	0
////coupon_amount	decimal	10	2	0	0	0	0			0.00	优惠金额					0	0	0	0	0	0	0
////refund_type	tinyint	1	0	0	0	0	0			0	退款类型 1-当日退款  2-隔日退					0	0	0	0	0	0	0
//        $logList = $query->select([
//            "day", "agent_id", "store_id", "receive_model", "ways_type", "pay_type",
//            DB::raw("sum(total_fee) as total_fee"),//总金额
//            DB::raw("sum(fee_amount) as fee_amount"),//手续费
//            DB::raw("sum(fee_commission) as fee_commission"),//分润金额
//            DB::raw("sum(refund_fee) as refund_fee"),//总金额
//            DB::raw("sum(oem_profit) as oem_profit"),//oem收益
//            DB::raw("sum(oem_fee) as oem_fee"), //oem实收
//            DB::raw("sum(agent1_profit) as agent1_profit"),//1级代理商收益
//            DB::raw("sum(agent1_fee) as agent1_fee"),//1级代理商实收
//            DB::raw("sum(agent2_profit) as agent2_profit"),//2级代理商收益
//            DB::raw("sum(agent2_fee) as agent2_fee"),//2级代理商实收
//            DB::raw("sum(agent3_profit) as agent3_profit"),//3级代理商收益
//            DB::raw("sum(agent3_fee) as agent3_fee"),//3级代理商实收
//            DB::raw("sum(agent4_profit) as agent4_profit"),//4级代理商收益
//            DB::raw("sum(agent4_fee) as agent4_fee"),//4级代理商实收
//            DB::raw("")
//        ])
//            ->where($where)
//            ->groupBy([
//                "day", "agent_id", "store_id", "receive_model", "ways_type", "pay_type", "company", ""
//            ])
//            ->get()->toArray();
//        //合并数据
//        $load = new LoadRelationDataService();
//        list($logList, $modelCollection) = $load->mergeData($logList, [1, 2, 3, 4]);
//        unset($modelCollection);
//        return $logList;
//    }


}